from django.shortcuts import render_to_response
from django.template import RequestContext

from django.http import HttpResponseRedirect, Http404
from django.contrib.auth.models import User

from django.utils.datastructures import MultiValueDictKeyError

from komuna.frontend.models import News, Project, Label

# Create your views here.
def index(request):
	news = News.objects.order_by('-publishDate')[:5]
	recent = Project.objects.order_by('-lastChange')[:5]
	return render_to_response('index.html', {'news':news, 'recent':recent}, context_instance=RequestContext(request))

def projectOverview(request):
	myProjects = []
	if request.user.is_authenticated():
		myProjects = request.user.project_set.all()
	else:
		return HttpResponseRedirect('login')
	return render_to_response('projectOverview.html', {'myProjects':myProjects}, context_instance=RequestContext(request))

def projectDetails(request):
	try:
		name = request.GET['name']
	except MultiValueDictKeyError:
		raise Http404
	proj = Project.objects.get(shortName=name)
	members = proj.members.all()
	return render_to_response('projectDetails.html', {'project':proj, 'members':members}, context_instance=RequestContext(request))

def search(request):
	try:
		name = request.POST['projectname']
	except MultiValueDictKeyError:
		raise Http404
	proj = Project.objects.filter(title__icontains=name)
	return render_to_response('search.html', {'projects':proj}, context_instance=RequestContext(request))

def newProject(request):
	if not request.user.is_authenticated():
		return HttpResponseRedirect('login')
	if request.method == "POST":
		pass
	else:
		labels = Label.objects.all()
		return render_to_response('newProject.html', {'labels':labels },context_instance=RequestContext(request))

